#include<vector>
using std::vector;


struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};



class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*> pathP = {root};
        findPath(p, pathP);
        vector<TreeNode*> pathQ = {root};
        findPath(q, pathQ);
        // iter 2 vector to find nearest ans
        TreeNode* ans = root;
        for (int i = 1; i < pathP.size() && i < pathQ.size(); i++) {
            if (pathP[i] == pathQ[i]) ans = pathP[i];
            else break;
        }
        return ans;
    }

    bool findPath(TreeNode* p, vector<TreeNode*>& path) {
        if (path.empty()) return false;
        if (path.back() == p) return true;
        TreeNode* curNode = path.back();
        if (curNode->left) {
            path.push_back(curNode->left);
            if (findPath(p, path)) return true;
            path.pop_back();
        }
        if (curNode->right) {
            path.push_back(curNode->right);
            if (findPath(p, path)) return true;
            path.pop_back();
        }
        return false;
    }
};